<?php

namespace App\Logics;


use App\Models\Event;
use App\Models\Order;
use App\Models\User;
use App\Models\UserMoney;
use App\Models\UserProfit;
use App\Models\UserProfit2;
use App\Models\UserWithdraw;
use App\Service\Base\Logic;


class MoneyLogic extends Logic
{


    // 用于收益明细 每一笔订单合并
    public function myProfit2($myUid)
    {
        $opt    = $this->option();
        $page   = $opt->getData('page', 1, 'intval');
        $rows   = $opt->getData('rows', 15, 'intval');
        $f_uid  = $opt->getData('form_uid', 0, 'intval');
        $s_time = $opt->getData('start_time', 0, 'intval');
        $e_time = $opt->getData('end_time', 0, 'intval');

        // 模型 和 查询  ->isCache($this->listCache)
        $start = ($page - 1) * $rows;
        $where = [['uid', '=', $myUid]];
        $bang  = ['uid'];
        if($f_uid){
            $bang[]  = 'form_uid';
            $where[] = ['form_uid', '=', $f_uid];
        }
        if($s_time){
            $bang[]  = 'ctime';
            $where[] = ['ctime', '>=', $s_time];
        }
        if($e_time){
            $bang[]  = 'ctime';
            $where[] = ['ctime', '<=', $e_time];
        }

        // 模型
        $model  = new UserProfit2();
        $KCache = $model->cacheKey('lists', $where);
        $result = $model->cacheClass()->getCache($KCache);
        // 检查是否已经绑定
        if(($result) && (!empty($result['list']))){
            $model->checkBangList($result['list'], $KCache);
        }
        if(empty($result)){
            $result = $model->bangField($bang)->listPage($where, $page, $rows, "id DESC");
            //$lists = $model->bangField($bang)->getList($where, $rows, "id DESC", $start);
            //$lists = is_object($lists) ? $lists->toArray() : $lists;
            if($where != false){
                $model->addCacheList($result['list'], $KCache, $result, 'list');
            }
        }
        // 组合用户
        if(!empty($result['list'])){
            $fromUids = array_column($result['list'], 'form_uid');
            $orderIds = array_column($result['list'], 'order_id');
            $users    = (new User())->isCache(true)->getListInIds($fromUids);
            $orders   = (new Order())->isCache(true)->getListInIds($orderIds);
            $eventIds = array_column($orders, 'event_id');
            $events   = (new Event())->isCache(true)->getListInIds($eventIds);

            // 组合
            foreach($result['list'] as &$item){
                $form_uid  = $item['form_uid'];
                $order_id  = $item['order_id'];
                $orderInfo = $orders[$order_id] ?? [];
                $event_id  = $orderInfo['event_id'] ?? 0;

                // 来源用户
                $item['from_user'] = $users[$form_uid] ?? (object)[];
                $item['order']     = $orderInfo ?: (object)[];
                $item['event']     = $events[$event_id] ?? (object)[];
            }
        }


        return $result;
    }


    // 用于收益明细
    public function myProfit($myUid)
    {
        $opt    = $this->option();
        $page   = $opt->getData('page', 1, 'intval');
        $rows   = $opt->getData('rows', 15, 'intval');
        $f_uid  = $opt->getData('form_uid', 0, 'intval');
        $s_time = $opt->getData('start_time', 0, 'intval');
        $e_time = $opt->getData('end_time', 0, 'intval');

        // 模型 和 查询  ->isCache($this->listCache)
        $start = ($page - 1) * $rows;
        $where = [['uid', '=', $myUid]];
        $bang  = ['uid'];
        if($f_uid){
            $bang[]  = 'form_uid';
            $where[] = ['form_uid', '=', $f_uid];
        }
        if($s_time){
            $bang[]  = 'ctime';
            $where[] = ['ctime', '>=', $s_time];
        }
        if($e_time){
            $bang[]  = 'ctime';
            $where[] = ['ctime', '<=', $e_time];
        }

        // 模型
        $model  = new UserProfit();
        $KCache = $model->cacheKey('lists', $where);
        $lists  = $model->cacheClass()->getCache($KCache);
        // 检查是否已经绑定
        if(!empty($lists)){
            $model->checkBangList($lists, $KCache);
        }
        if(empty($lists)){
            //$result = $model->bangField($bang)->listPage($where, $page, $rows, "id DESC");
            $lists = $model->bangField($bang)->getList($where, $rows, "id DESC", $start);
            $lists = is_object($lists) ? $lists->toArray() : $lists;
            if($where != false){
                $model->addCacheList($lists, $KCache, $lists, 'list');
            }
        }

        return $lists;
    }

    // 用于余额变化明细
    public function myMoney($myUid)
    {
        $opt    = $this->option();
        $page   = $opt->getData('page', 1, 'intval');
        $rows   = $opt->getData('rows', 15, 'intval');
        $f_uid  = $opt->getData('form_uid', 0, 'intval');
        $s_time = $opt->getData('start_time', 0, 'intval');
        $e_time = $opt->getData('end_time', 0, 'intval');


        // 模型 和 查询  ->isCache($this->listCache)
        $start = ($page - 1) * $rows;
        $where = [['uid', '=', $myUid]];
        $bang  = ['uid'];
        if($f_uid){
            $bang[]  = 'form_uid';
            $where[] = ['form_uid', '=', $f_uid];
        }
        if($s_time){
            $bang[]  = 'ctime';
            $where[] = ['ctime', '>=', $s_time];
        }
        if($e_time){
            $bang[]  = 'ctime';
            $where[] = ['ctime', '<=', $e_time];
        }


        // 模型
        $model  = new UserMoney();
        $KCache = $model->cacheKey('lists', $where);
        $lists  = $model->cacheClass()->getCache($KCache);
        // 检查是否已经绑定
        if(!empty($lists)){
            $model->checkBangList($lists, $KCache);
        }

        if(empty($lists)){
            //$result = $model->bangField($bang)->listPage($where, $page, $rows, "id DESC");
            $lists = $model->bangField($bang)->getList($where, $rows, "id DESC", $start);
            $lists = is_object($lists) ? $lists->toArray() : $lists;
            if($where != false){
                $model->addCacheList($lists, $KCache, $lists, 'list');
            }
        }

        return $lists;
    }

    // 提现明细
    public function myWithdraw($myUid)
    {
        $opt   = $this->option();
        $page  = $opt->getData('page', 1, 'intval');
        $rows  = $opt->getData('rows', 15, 'intval');
        $start = ($page - 1) * $rows;


        // 模型 和 查询  ->isCache($this->listCache)
        $where  = [['uid', '=', $myUid]];
        $bang   = ['uid'];
        $s_time = $opt->getData('start_time', 0, 'intval');
        $e_time = $opt->getData('end_time', 0, 'intval');
        if($s_time){
            $bang[]  = 'ctime';
            $where[] = ['ctime', '>=', $s_time];
        }
        if($e_time){
            $bang[]  = 'ctime';
            $where[] = ['ctime', '<=', $e_time];
        }

        // 模型
        $model  = new UserWithdraw();
        $KCache = $model->cacheKey('lists', $where);
        $lists  = $model->cacheClass()->getCache($KCache);
        // 检查是否已经绑定
        if(!empty($lists)){
            $model->checkBangList($lists, $KCache);
        }

        if(empty($lists)){
            //$result = $model->bangField($bang)->listPage($where, $page, $rows, "id DESC");
            $lists = $model->bangField($bang)->getList($where, $rows, "id DESC", $start);
            $lists = is_object($lists) ? $lists->toArray() : $lists;
            if($where != false){
                $model->addCacheList($lists, $KCache, $lists, 'list');
            }
        }

        return $lists;
    }


    // 提现
    public function onWithdraw($myUid)
    {
        // 参数
        $opt   = $this->option();
        $money = $opt->getData("money", null, "trim");
        $data  = [
            'uid'         => $myUid,
            'trade_no'    => $myUid.'A'.date("YmdHis").'A'.random(4),  // 提现的时候必须是数字和字母
            'money'       => $money,
            'description' => $opt->getData("description", null, "trim"),
            //'ctime'     => $opt->getData("ctime", null, "intval"),
            //'mtime'     => $opt->getData("mtime", null, "intval"),
        ];
        if($money < 0){
            return $this->_returnFail('提现金额不能为负！');
        }
        if($money > 500){
            return $this->_returnFail('提现金额不能超过500！');
        }

        $data = $this->filterNull($data);
        if(empty($data)){
            return $this->_returnFail('请添加需要保存的数据！');
        }

        // 判断是否已经有提现了
        $model = new UserWithdraw();
        $info  = $model->isCache(true)->oneFind(['uid' => $myUid, 'verify' => 0]);
        if($info){
            return $this->_returnFail('你已经有提现的订单了！');
        }

        // 检查用户今天提现金额 每天不能超过2w
        $_stamp = strtotime("today");
        $lists  = $model->where([['uid', '=', $myUid], ['mtime', '>=', $_stamp]])->get()->toArray();
        $allMon = $money;
        foreach($lists as $_item){
            $allMon = $allMon + $_item['money'];
        }
        if($allMon > 20000){
            return $this->_returnFail('对不起，你今天提醒金额不能大于2万！');
        }

        // 检查用户金额
        $userInfo = (new User())->isCache(true)->getOneById($myUid);
        if(empty($userInfo)){
            return $this->_returnFail('你的用户信息不存在！');
        }
        if($userInfo['money'] < $money){
            return $this->_returnFail('你的余额不足！');
        }

        // 组合数据
        $result = $model->checkRules($data, 'add');
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        // 保存
        $result = $model->oneAdd($data);
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        return $result;
    }

    // 改变（直接修改，软删除，改变状态，排序）
    public function onEdit($myUid)
    {
        $_id = $this->id();
        if(empty($_id)){
            return $this->_returnFail('请指定修改的ID编号！');
        }

        $opt  = $this->option();
        $data = [
            //'id'          => $opt->getData("id", null, "intval"),
            //'uid'         => $myUid,
            'form_uid'    => $opt->getData("form_uid", null, "intval"),
            'total'       => $opt->getData("total", null, "trim"),
            'money'       => $opt->getData("money", null, "trim"),
            'type'        => $opt->getData("type", null, "trim"),
            'description' => $opt->getData("description", null, "trim"),
            //'ctime'       => $opt->getData("ctime", null, "intval"),
            //'mtime'       => $opt->getData("mtime", null, "intval"),
        ];

        $data = $this->filterNull($data);
        if(empty($data)){
            return $this->_returnFail('请添加需要保存的数据！');
        }

        // 组合数据
        $where = ['id' => $_id, 'uid' => $myUid];
        $model = new UserMoney();
        $data  = $model->checkData($data, $where);
        if($data === false){
            return $this->_returnFail('请添加需要保存的数据！');
        }

        // 验证
        $result = $model->checkRules($data, 'edit');
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        // 保存
        $result = $model->oneEdit($where, $data);
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        return $result;
    }

    // 树状
    public function onAdd($myUid)
    {
        $opt  = $this->option();
        $data = [
            //'id'          => $opt->getData("id", null, "intval"),
            'uid'         => $myUid,
            'form_uid'    => $opt->getData("form_uid", null, "intval"),
            'total'       => $opt->getData("total", null, "trim"),
            'money'       => $opt->getData("money", null, "trim"),
            'type'        => $opt->getData("type", null, "trim"),
            'description' => $opt->getData("description", null, "trim"),
            //'ctime'       => $opt->getData("ctime", null, "intval"),
            //'mtime'       => $opt->getData("mtime", null, "intval"),
        ];

        $data = $this->filterNull($data);
        if(empty($data)){
            return $this->_returnFail('请添加需要保存的数据！');
        }

        // 组合数据
        $model = new UserMoney();
        $data  = $model->checkData($data);
        if($data === false){
            return $this->_returnFail('请添加需要保存的数据！');
        }

        // 验证
        $result = $model->checkRules($data, 'add');
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        // 保存
        $result = $model->oneAdd($data);
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        return $result;
    }

}


